package xyz;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;

import java.io.InputStream;
import java.net.URL;


/**
 * @Title: xyz
 * @author: Sunne
 * @date: 2024-12-08 上午10:13
 * @Description: 代码备注说明
 */
public class HelloFC implements PojoRequestHandler<FlieSaveDownDto, FlieSaveDownDto> {
    private static final String ENDPOINT = "https://oss-cn-shanghai-internal.aliyuncs.com"; // 例如：https://oss-cn-hangzhou.aliyuncs.com
//    private static final String ACCESS_KEY_ID = "LTAI5tLEqDgixECTnRbXzTS1";
//    private static final String ACCESS_KEY_SECRET = "EVafnha5xj5o5wYxPxQYS3YKyLXjBg";
    private static final String BUCKET_NAME = "aivitts";
    private static final String region = "cn-shanghai";

    @Override
    public FlieSaveDownDto handleRequest(FlieSaveDownDto flieSaveDownDto, Context context) {
        String fileURL = flieSaveDownDto.getDownpath();
        String saveFilePath = flieSaveDownDto.getSavepath();

        try {
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 创建OSSClient实例。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            OSS ossClient = OSSClientBuilder.create()
                    .endpoint(ENDPOINT)
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();
            try {
                InputStream inputStream = new URL(fileURL).openStream();
                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, saveFilePath, inputStream);
                // 创建PutObject请求。
                PutObjectResult result = ossClient.putObject(putObjectRequest);
            }finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return flieSaveDownDto;
    }

}
